<?php
namespace PsiFramework\Applications\DefaultApp\Classes\Actions\Util;

use PsiFramework\Classes\Util\HTTP\HTTPRequest;

use \PsiFramework\Classes\Actions\AbstractAction;

/**
 * PsiFramework
 * Php Simple Framework
 *
 * @author Rémi San
 * @version beta
 */

/**
 * The Proxy Action
 *
 * This action is used for proxy operations
 *
 * @package Actions.Util
 */
class ProxyAction extends AbstractAction
{

    protected function replaceLink($string, $baseUrl)
    {
        $string = preg_replace('/href="((?!http)[^"]+)"/', 'href="'.$baseUrl.'\\1"', $string);
        
        return $string;
    }
    
    protected function replaceCssLink($string, $baseUrl)
    {
        $string = preg_replace('/url\(((?!http)[^)]+)\)/', 'url('.$baseUrl.'\\1)', $string);
    
        return $string;
    }
    
    /**
     * Function executed by the controller
     *
     * Uses a proxy
     *
     * @return Response the response to the action execution
     */
    public function execute()
    {
        parent::execute();
        
        $url = $this->_request->getParameter('url');
        $req = new HTTPRequest($url);
        
        $contentType = null;
        $response = $req->execute(HTTPRequest::$get, $contentType);
        
        header_remove('content-type');
        if (!isNullOrEmptyString($contentType)) {
            header($contentType);
        }

        $baseUrl = substr($url, 0, strripos($url, '/')+1);
        
        $response = $this->replaceCssLink($response, $baseUrl);
        $response = $this->replaceLink($response, $baseUrl);
        
        echo $response;
        
        exit;
    }
}
